//
//  UITextField+MaximumLimit.swift
//  
//
//  Created by tangbl93 on 2021/1/6.
//

import UIKit

private class YXCalcMaximumLimit {
    
    /// calculation should change characters
    // TODO: cutting function
    static func yx_calcMaximumLimit(_ text:String?, range: NSRange, replacementString string: String, maximumLimit:Int?) -> Bool {
        guard let maximumLimit = maximumLimit else { return true }
        
        let oldLength = text?.count ?? 0
        let replacementLength = string.count
        let rangeLength = range.length
        
        let lastLength = oldLength - rangeLength + replacementLength
        let returnKey  = string == String.yx_keyboardReturn

        return lastLength <= maximumLimit || returnKey
    }
}

public extension UITextField {
    
    func yx_calcMaximumLimit(_ range: NSRange, replacementString string: String, maximumLimit:Int?) -> Bool {
        return YXCalcMaximumLimit.yx_calcMaximumLimit(self.text, range: range, replacementString: string, maximumLimit: maximumLimit)
    }
}

public extension UITextView {
    
    func yx_calcMaximumLimit(_ range: NSRange, replacementString string: String, maximumLimit:Int?) -> Bool {
        return YXCalcMaximumLimit.yx_calcMaximumLimit(self.text, range: range, replacementString: string, maximumLimit: maximumLimit)
    }
}
